import React, { useEffect, useState } from "react";
import { NavBar } from "antd-mobile";
import "./index.scss";
import { useNavigate, useParams } from "react-router-dom";
import { courseDetailGet } from "../../api/course";
import { CourseType } from "@/types/course";
import { useUserStore } from "@/store/user";
import { userCollect, userCollectDel, userCollectGet } from "@/api/user";
type Props = {};

export default function Detail({}: Props) {
  const params = useParams();
  const [detail, setDetail] = useState<CourseType>();
  const [collect, setCollect] = useState<boolean>(false); //控制收藏状态
  const { userInfo } = useUserStore((state) => state);
  const [collectId, setCollectId] = useState<string>("");
  const navigate = useNavigate();
  // console.log(params);
  useEffect(() => {
    // 获取详情
    courseDetailGet(params.id as string).then((res) => {
      // console.log(res);
      setDetail(res.data);
    });

    //获取收藏状态
    let courseid = params.id;
    let userid = userInfo?.objectId;
    userCollectGet({ courseid, userid }).then((res) => {
      // console.log(res);
      if (res.data.results.length) {
        setCollect(true);
        let { objectId } = res.data.results[0];
        setCollectId(objectId); //记录收藏id
      }
    });
  }, []);
  //收藏
  const handleCollect = () => {
    if (!userInfo) {
      navigate("/login");
    } else {
      let { name, poster, isvip, info, objectId } = detail as CourseType;
      let userid = userInfo.objectId;
      let courseid = objectId;
      userCollect({ name, poster, isvip, info, userid, courseid }).then(
        (res) => {
          console.log(res);
          setCollect(true);
          let { objectId } = res.data;
          setCollectId(objectId); //记录收藏id
        }
      );
    }
  };
  // 取消收藏
  const handleRemove = () => {
    console.log("取消收藏");
    userCollectDel(collectId).then((res) => {
      setCollect(false);
    });
  };

  const handleBack = () => {
    navigate(-1);
  };
  const right = (
    <>
      {collect ? (
        <i className="iconfont jushoucanggift" onClick={handleRemove}></i>
      ) : (
        <i className="iconfont jushoucang" onClick={handleCollect}></i>
      )}
    </>
  );
  return (
    <div className="detail-cont">
      <NavBar onBack={handleBack} right={right}>
        课程详情
      </NavBar>
      <div className="detail">
        {detail ? (
          <>
            <img src={detail.poster} alt="" />
            <h2>{detail.name}</h2>
            {userInfo ? (
              <div dangerouslySetInnerHTML={{ __html: detail.desc }}></div>
            ) : (
              <p>{detail.info}</p>
            )}
          </>
        ) : (
          ""
        )}
      </div>
    </div>
  );
}
